//
//  XHCollectionViewController.m
//  Big Show
//
//  Created by 赵晓航 on 15-5-13.
//  Copyright (c) 2015年 Big_Q. All rights reserved.
//

#import "XHCollectionViewController.h"
#import "XHCollectionObject.h"
#import "XHMyTableViewCell.h"
#import "XHEditxiangViewController.h"
#import "XHbameiViewController.h"
#import "UIImageView+WebCache.h"
#import "XH12TableViewCell.h"
#import "WX12TableViewCell.h"

@interface XHCollectionViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) NSMutableArray *mArr;
@property (nonatomic, retain) NSMutableArray *arrrr;
@property (nonatomic, retain) UIImageView *img;

@end

@implementation XHCollectionViewController

- (void)dealloc
{
    [_tableView release];
    [_img release];
    [_mArr release];
    [_arrrr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"收藏";
    self.navigationController.navigationBar.translucent = NO;
    
    [self getManagerWithFind];
    [self createImageView];
    [self createTableView];

    
    
}


- (void)createImageView
{
    self.img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _img.image = [UIImage imageNamed:@"u=2916742164,3184761356&fm=21&gp=0.jpg"];
    [self.view addSubview:_img];
    [_img release];

    
}



- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49 - 64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight = 150;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    [_tableView release];
    // 开启tableView的编辑状态
    // 通过系统提供的编辑按钮手动开启或者关闭编辑状态
    // 1.设置编辑按钮
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arrrr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int aa = 0;
    NSDictionary *dic = [_arrrr objectAtIndex:indexPath.row];
    NSArray *arr = [dic allKeys];
    for (NSString *str in arr) {
        if ([str isEqualToString:@"docid"]) {
            aa = 1;
        }
    }
    
    if (aa == 1) {
        NSArray *arr = [[_arrrr objectAtIndex:indexPath.row] objectForKey:@"image_urls"];
        if (arr.count < 3) {
            XH12TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
            if (cell == nil) {
                cell = [[[XH12TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
                cell.backgroundColor = [UIColor clearColor];
            }
            [cell setDic:[_arrrr objectAtIndex:indexPath.row]];
            return cell;
            
        }else{
            WX12TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
            if (!cell) {
                cell = [[[WX12TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"] autorelease];
                cell.backgroundColor = [UIColor clearColor];
            }
            
            [cell setDic: [_arrrr objectAtIndex:indexPath.row]];
            return cell;
        }
        
    }else{
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"celll"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"celll"];
        }
        
        cell.backgroundColor = [UIColor clearColor];
        
        cell.textLabel.text = [_arrrr[indexPath.row] objectForKey:@"title"];
        
        return cell;
    }

}


- (void)getManagerWithFind
{
    NSString *path = [[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"kof"] stringByAppendingPathComponent:@"kof.duang"];
    self.arrrr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}


-(void)viewDidAppear:(BOOL)animated
{
    
    [self getManagerWithFind];
    
    [_tableView reloadData];
    
}


// 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    int aa = 0;
    NSDictionary *dic = [_arrrr objectAtIndex:indexPath.row];
    NSArray *arr = [dic allKeys];
    for (NSString *str in arr) {
        if ([str isEqualToString:@"docid"]) {
            aa = 1;
        }
    }
    
    if (aa == 0) {
        XHbameiViewController *bamei = [[XHbameiViewController alloc] init];
        bamei.mDic = dic;
        [self.navigationController pushViewController:bamei animated:YES];
    }else{
    XHEditxiangViewController *x = [[XHEditxiangViewController alloc] init];
    x.docid = [[_arrrr objectAtIndex:indexPath.row] objectForKey:@"docid"];
    [self.navigationController pushViewController:x animated:YES];
    }
}
#pragma mark - tableView编辑方法
#warning 1. 开启编辑状态
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    // 调用父类的方法
    [super setEditing:editing animated:animated];
    
    // 利用系统的编辑按钮控制tableView编辑状态
    [_tableView setEditing:editing animated:animated];
}
#warning 2. 是否允许编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
#warning 3. 设计编辑的样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 通过indxpath控制编辑样式
    return UITableViewCellEditingStyleDelete;
    
}
#warning 4. 判断编辑状态进行删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 通过editingStyle判断状态  执行删除
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        NSString *path = [[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"kof"] stringByAppendingPathComponent:@"kof.duang"];
        // 创建一个文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        [fileManager removeItemAtPath:path error:nil];
        
        // 1. 删除数据
        [_arrrr removeObjectAtIndex:indexPath.row];
        // 2. 删除的信息需要被存放在一个数组中
        NSArray *arr = @[indexPath];
        // 3. 让视图和数据匹配
        // 参数1: 删除信息的数组
        // 参数2: 删除操作的效果
        [_tableView deleteRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationTop];
        
        // 归档
        [NSKeyedArchiver archiveRootObject:_arrrr toFile:path];
    }
}
// 删除样式(确定删除)
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
    
}

// 把原下标处的cell删除
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    
    NSString *path = [[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"kof"] stringByAppendingPathComponent:@"kof.duang"];
    // 创建一个文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    [fileManager removeItemAtPath:path error:nil];
    
    
    // 1. 设置临时变量 保存数据
    NSString *temp = [_arrrr[sourceIndexPath.row] retain];
    // 2. 从原位置删除数据
    [_arrrr removeObjectAtIndex:sourceIndexPath.row];
    // 3. 添加到新的位置
    [_arrrr insertObject:temp atIndex:destinationIndexPath.row];
    // 释放
    [temp release];
    
    // 归档
    [NSKeyedArchiver archiveRootObject:_arrrr toFile:path];
}

// 限制跨区移动
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    // 判断原位置和预期位置  是否在一个区域内
    // 如果在  则允许删除
    if (sourceIndexPath.section == proposedDestinationIndexPath.section) {
        return proposedDestinationIndexPath;
    }else{
        // 否则 不允许删除
        return sourceIndexPath;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    self.tabBarController.tabBar.tintColor = [UIColor magentaColor];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
